#!/usr/bin/perl
#!/usr/bin/perl
use strict;
use FindBin;
use JSON;
use Getopt::Long;
use File::Glob qw(bsd_glob);
use Cwd;

use ServerAdapter;
use TarSCPExec;
use DeployUtils;
use DeployLock;

sub usage {
    my $pname = $FindBin::Script;

    print("Usage: $pname [--envpath EnvPath] [--version VERSION]\n");
    print("              [--verbose 0|1] [--cpifexists 0|1] [--followlinks 0|1] [--pull 0|1]\n");
    print("              [--pdir approot|project|release|appdist|dbscript|mirror]\n");
    print("              <src> <dest>\n");
    print("\n");
    print("       --envpath: Env path in the data directory, example:ATM/ATMP/PRD/ATMP-1\n");
    print("       --version: version number of sub system\n");
    print("       --cpifexists: copy if local dir or file exists.\n");
    print("       --pull: pull from remote site to local site\n");

    exit(-1);
}

sub main {
    my ( $isHelp, $isVerbose, $envPath, $version );
    my ( $isPull, $isPush, $cpIfExists, $followLinks, $pdir, $node );

    my $pname = $FindBin::Script;

    $isPull      = 0;
    $isVerbose   = 0;
    $followLinks = 0;
    $pdir        = 'appdist';

    GetOptions(
        'h|help'         => \$isHelp,
        'v|verbose=i'    => \$isVerbose,
        'envpath=s{0,1}' => \$envPath,
        'version=s'      => \$version,
        'pull=i'         => \$isPull,
        'cpifexists=i'   => \$cpIfExists,
        'followlinks=i'  => \$followLinks,
        'pdir=s'         => \$pdir,
        'node=s'         => \$node,
        '<>'             => \&pushItems
    );

    usage() if ( defined($isHelp) );

    my ( @items, @dirs );

    sub pushItems {
        my ($item) = @_;
        push( @items, $item );
    }

    my $deployUtils = DeployUtils->new();

    my $optionError = 0;

    if ( scalar(@items) < 2 ) {
        print("ERROR: Must define local path and remote path.\n");
        $optionError = 1;
    }

    for ( my $i = 0 ; $i < scalar(@items) ; $i++ ) {
        my $dir = $items[$i];
        if ( $dir =~ /\/\.\.\// or $dir =~ /^\.\.\// or $dir =~ /\/\.\.$/ ) {
            print("ERROR: Path can not has parent dir opertor:\"..\".\n");
            $optionError = 1;
        }
        else {
            $dir = $deployUtils->charsetConv( $items[$i], 'utf-8' );
            $items[$i] = $dir;
        }
    }

    my $deployEnv = $deployUtils->deployInit( $envPath, $version );
    $envPath = $deployEnv->{NAME_PATH};
    $version = $deployEnv->{VERSION};

    if ( not defined($envPath) or $envPath eq '' ) {
        $optionError = 1;
        print("ERROR: EnvPath not defined by option --envpath or Environment:NAME_PATH\n");
    }
    if ( not defined($version) or $version eq '' ) {
        $optionError = 1;
        print("ERROR: Version not defined by option --version or Environment:VERSION\n");
    }

    my $namePath = $deployEnv->{NAME_PATH};
    my $envName  = $deployEnv->{ENV_NAME};

    my $serverAdapter = ServerAdapter->new();

    my $verInfo   = $serverAdapter->getEnvVer( $deployEnv, $version );
    my $verStatus = $verInfo->{status};
    my $buildNo   = $verInfo->{buildNo};
    if ( $verInfo->{status} ne 'released' ) {
        print("ERROR: $namePath version:$version is not released to $envName.\n");
        return 3;
    }

    my $dirInfo = $deployUtils->getDataDirStruct($deployEnv);
    my $verPath = $dirInfo->{$pdir};

    if ( defined($pdir) ) {
        if ( not defined($verPath) ) {
            print("ERROR: $pdir not valid, not in appsync|mirror|appbuild|version.\n");
            $optionError = 1;
        }
    }

    my $nodeInfo = $deployUtils->getNodeInfo($node);
    if ( not $nodeInfo ) {
        $optionError = 1;
        print("ERROR: Execute node json not defined by environment AUTOEXEC_NODE or option --node\n");
    }

    if ( $optionError == 1 ) {
        usage();
    }

    my ( @srcs, $dest );
    $dest = pop(@dirs);

    my $direction = 'push';
    if ( $isPull == 1 ) {
        $direction = 'pull';
    }

    my $envName = $deployEnv->{ENV_NAME};
    my $verRoot = $dirInfo->{appRoot};

    my $host  = $nodeInfo->{host};
    my $port  = $nodeInfo->{protocolPort};
    my $user  = $nodeInfo->{username};
    my $pass  = $nodeInfo->{password};
    my $insId = $nodeInfo->{resourceId};

    #my $insName = $nodeInfo->{nodeName};
    my $insUniqName = $nodeInfo->{nodeUniqName};

    if ( defined($pass) and $pass ne '' ) {
        $pass = $deployUtils->decryptPwd($pass);
    }

    $port = 22 if ( not defined($port) );

    my $lock      = DeployLock->new($deployEnv);
    my $appLockId = $lock->lockEnvApp($DeployLock::WRITE);

    END {
        local $?;
        if ( defined($lock) ) {
            $lock->unlockEnvApp($appLockId);
        }
    }

    my $verDiffPath = "$verPath.ins/$insUniqName";

    if ( $isPull eq 0 ) {
        foreach my $dir (@items) {
            my $aSrc         = "$verPath/$dir";
            my @aSrcExpanded = bsd_glob($aSrc);

            if ( scalar(@aSrcExpanded) == 0 ) {
                if ( defined($cpIfExists) ) {
                    print("WARN: The src $aSrc does not match any file!\n");
                    next;
                }
            }

            foreach my $d (@aSrcExpanded) {
                push( @dirs, $d );
            }

            my $hasDiff  = 0;
            my @diffDirs = bsd_glob("$verDiffPath/$dir");
            foreach my $diffDir (@diffDirs) {
                if ( -e $diffDir ) {
                    $hasDiff = 1;
                    last;
                }
            }
            if ( $hasDiff == 1 ) {
                push( @dirs, "$verDiffPath/$dir" );
            }
        }
    }
    else {
        @dirs = @items;
    }

    my $hasError = 0;
    if ( $isPull eq 1 ) {
        $dest = "$verPath/$dest";

        foreach my $dir (@dirs) {
            if ( $dir =~ /^\.\.\// or $dir =~ /\/\.\.$/ or $dir =~ /\/\.\.\// ) {
                print("ERROR: FileTrans name can not has '..':$dir.\n");
                exit(-1);
            }

            my $tarScpExec = new TarSCPExec(
                host        => $host,
                port        => $port,
                username    => $user,
                password    => $pass,
                source      => $dir,
                destination => $dest,
                isPull      => 1,
                followLinks => $followLinks,
                verbose     => $isVerbose
            );

            my $rc = $tarScpExec->exec();

            if ( $rc == 0 ) {
                print("FINE: Pull $host:$dir to $dest success.\n");
            }
            else {
                $hasError = $hasError + $rc;
                print("ERROR: Pull $host:$dir to $dest failed.\n");
                last;
            }
        }
    }
    else {
        foreach my $dir (@dirs) {
            if ( $dir =~ /^\.\.\// or $dir =~ /\/\.\.$/ or $dir =~ /\/\.\.\// ) {
                $hasError = $hasError + 1;
                print("ERROR: File name can not has '..':$dir.\n");
                exit($hasError);
            }
            my $tarScpExec = new TarSCPExec(
                host        => $host,
                port        => $port,
                username    => $user,
                password    => $pass,
                source      => $dir,
                destination => $dest,
                isPull      => 0,
                followLinks => $followLinks,
                verbose     => $isVerbose
            );

            my $rc = $tarScpExec->exec();

            if ( $rc == 0 ) {
                print("FINE: Push $dir to $host:$dest success.\n");
            }
            else {
                $hasError = $hasError + $rc;
                print("ERROR: Push $dir to $host:$dest failed.\n");
                last;
            }
        }
    }

    if ( $hasError > 0 ) {
        print( "ERROR: $pname --$direction " . join( ' ', @dirs ) . " failed.\n" );
    }

    return $hasError;
}

exit main();
